package Fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

import Database.SQLquery;
import barcode.code.nhat.iuhbarcode.Camera_Lib;
import barcode.code.nhat.iuhbarcode.Main_Action;
import barcode.code.nhat.iuhbarcode.R;

public class Zbar_fragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public Zbar_fragment() {
    }

    public static Zbar_fragment newInstance(int sectionNumber, String name) {
        class_name = name;
        Zbar_fragment fragment = new Zbar_fragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
    SimpleDateFormat date_format = new SimpleDateFormat("dd-MM-yyyy");

    private Camera mCamera;
    private Handler handler;
    private ImageScanner scanner;
    private Button bt_scan;
    private TextView scantext, resultText;
    private Spinner sp;

    private boolean barcodeScanned = false;
    private boolean previewing = true;
    private static String class_name;
    private SQLquery login;

    private int pos;
    private String[] Titles;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_zbar, container, false);
        Activity ac = getActivity();
        ac.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        bt_scan = (Button) v.findViewById(R.id.zbar_scan_bt);
        scantext = (TextView) v.findViewById(R.id.scanText);
        resultText = (TextView) v.findViewById(R.id.result);
        sp = (Spinner) v.findViewById(R.id.spinner_period);

        Titles = getResources().getStringArray(R.array.period);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, Titles);
        sp.setAdapter(dataAdapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                pos = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        login = new SQLquery(getActivity());
        login = login.open();

        handler = new Handler();
        mCamera = getCameraIntentce();

        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        Camera_Lib mPreview = new Camera_Lib(getActivity(), mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout) v.findViewById(R.id.camera_scan);
        preview.addView(mPreview);

        bt_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (barcodeScanned) {
                    barcodeScanned = false;
                    scantext.setText("Scanning...");
                    resultText.setText("");
                    mCamera.setPreviewCallback(previewCb);
                    mCamera.startPreview();
                    previewing = true;
                    mCamera.autoFocus(autoFocusCB);
                }
            }
        });
        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((Main_Action) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
    }

    static {
        System.loadLibrary("iconv");
    }

    public static Camera getCameraIntentce() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }

    Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();

            assert size != null;
            Image barcode = new Image(size.width, size.height, "Y800");
            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {
                previewing = false;
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();

                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {
                    if (sym.getData().length() > 8) {
                        scantext.setText("Barcode result");
                        resultText.setText("Not Found!");
                    } else if (sym.getData().length() == 8 || sym.getData() == null) {
                        scantext.setText("Barcode result");
                        resultText.setText(sym.getData());
                        login.insert_student_check(String.valueOf(sym.getData()), class_name, date_format.format(cal.getTime()), pos);
                    }
                    barcodeScanned = true;
                }
            }
        }
    };

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            handler.postDelayed(doAutoFocus, 1000);
        }
    };

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing) mCamera.autoFocus(autoFocusCB);
        }
    };

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    public void onPause() {
        super.onPause();
        releaseCamera();
    }

/*    @Override
    public void onDestroy() {
        super.onDestroy();
        login.close();
    }*/
}
